﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Activation;
using System.ServiceModel;
using Castle.Windsor;
using Castle.Windsor.Installer;
using Castle.MicroKernel.Registration;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using CHPM.IC.Logger;
using CHPM.IC.ServiceLocator;
using CHPM.SL.TheService.Code.ErrorHandling;
using log4net;

namespace CHPM.SL.TheService.Code
{
    public class MainServiceHostFactory : ServiceHostFactory
    {

        private static readonly IWindsorContainer _windsorContainer;
        private static readonly IServiceLocator _serviceLocator;

        static MainServiceHostFactory()
        {
            _windsorContainer = new WindsorContainer().Install(FromAssembly.This());
            _serviceLocator = new WindsorServiceLocator(_windsorContainer);
            _windsorContainer.Register(Component.For<IServiceLocator>().Instance(_serviceLocator));
            
        }

        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            Type serviceType = Type.GetType(constructorString);
            return CreateServiceHost(serviceType, baseAddresses);
        }

        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            IInstanceProvider serviceProvider = new ServiceLocatorInstanceProvider(serviceType, _serviceLocator);
            InstanceProviderBehavior instanceProviderBehavior = new InstanceProviderBehavior(serviceProvider);

            ILogger _errorLogger = _serviceLocator.Resolve<ILogger>();
            IServiceBehavior errorServiceBehavior = new ErrorServiceBehavior(_errorLogger);

            ServiceHost serviceHost = new DefaultServiceHost(
                serviceType
                , baseAddresses
                , new IServiceBehavior[] { instanceProviderBehavior, errorServiceBehavior });

            return serviceHost;
        }
    }
}